<template>
  <div class="app-container" v-loading="loading" element-loading-text="正在加载..." element-loading-spinner="el-icon-loading">
    <!-- 统计卡片 -->
    <div class="stat-cards-container">
      <div class="stat-card stat-card-primary" @click="handleCardClick('all')">
        <div class="stat-icon">
          <i class="el-icon-s-custom"></i>
        </div>
        <div class="stat-content">
          <div class="stat-number">{{ totalAppointmentCount }}</div>
          <div class="stat-label">预约总数</div>
        </div>
      </div>
      <div class="stat-card stat-card-success" @click="handleCardClick('2')">
        <div class="stat-icon">
          <i class="el-icon-check"></i>
        </div>
        <div class="stat-content">
          <div class="stat-number">{{ approvedCount }}</div>
          <div class="stat-label">审核通过</div>
        </div>
      </div>
      <div class="stat-card stat-card-danger" @click="handleCardClick('3')">
        <div class="stat-icon">
          <i class="el-icon-close"></i>
        </div>
        <div class="stat-content">
          <div class="stat-number">{{ rejectedCount }}</div>
          <div class="stat-label">审核拒绝</div>
        </div>
      </div>
      <div class="stat-card stat-card-info" @click="handleCardClick('4')">
        <div class="stat-icon">
          <i class="el-icon-remove"></i>
        </div>
        <div class="stat-content">
          <div class="stat-number">{{ cancelledCount }}</div>
          <div class="stat-label">已取消</div>
        </div>
      </div>
    </div>

    <!-- 图表和表格区域 -->
    <el-row :gutter="20">
      <!-- 左侧图表 -->
      <el-col :span="12">
        <div class="chart-container">
          <div class="chart-header">
            <h3 class="chart-title">科室预约占比</h3>
            <div></div>
          </div>
          <div class="chart-body">
            <pie-chart ref="pieChart" :width="'100%'" :height="'400px'" />
          </div>
        </div>
      </el-col>

      <!-- 右侧表格 -->
      <el-col :span="12">
        <div class="table-container">
          <div class="table-header">
            <h3 class="table-title">科室预约统计</h3>
            <el-button type="primary" size="small" :loading="loading" @click="refreshData">
              <i class="el-icon-refresh"></i> 刷新
            </el-button>
          </div>
          <div class="table-body">
            <el-table
              :data="deptStats"
              style="width: 100%"
              :header-cell-style="{background: '#f5f7fa', color: '#606266'}">
              <el-table-column label="科室名称" align="center" prop="deptName" />
              <el-table-column label="预约数量" align="center" prop="count" />
              <el-table-column label="占比" align="center">
                <template slot-scope="scope">
                  <span>{{ scope.row.percentage }}%</span>
                </template>
              </el-table-column>
              <el-table-column label="状态分布" align="center" width="220">
                <template slot-scope="scope">
                  <div class="status-tags">
                    <el-tag v-if="scope.row.approved > 0" type="success" size="mini">
                      通过: {{ scope.row.approved }}
                    </el-tag>
                    <el-tag v-if="scope.row.pending > 0" type="warning" size="mini">
                      待审: {{ scope.row.pending }}
                    </el-tag>
                    <el-tag v-if="scope.row.rejected > 0" type="danger" size="mini">
                      拒绝: {{ scope.row.rejected }}
                    </el-tag>
                    <el-tag v-if="scope.row.cancelled > 0" type="info" size="mini">
                      已取消: {{ scope.row.cancelled }}
                    </el-tag>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import PieChart from '@/views/dashboard/PieChart'
import request from '@/utils/request'
import { listDept } from '@/api/system/dept'

export default {
  name: 'Index',
  components: {
    PieChart
  },
  data() {
    return {
      // 统计数据
      totalAppointmentCount: 0,
      approvedCount: 0,
      rejectedCount: 0,
      cancelledCount: 0,
      // 加载状态
      loading: false,

      // 科室统计数据
      deptStats: [
        { deptId: '1', deptName: '办公室', count: 45, approved: 25, pending: 20, rejected: 0, percentage: 29 },
        { deptId: '2', deptName: '财务科', count: 38, approved: 20, pending: 18, rejected: 0, percentage: 24 },
        { deptId: '3', deptName: '人事科', count: 28, approved: 18, pending: 10, rejected: 0, percentage: 18 },
        { deptId: '4', deptName: '技术科', count: 25, approved: 15, pending: 10, rejected: 0, percentage: 16 },
        { deptId: '5', deptName: '业务科', count: 20, approved: 11, pending: 9, rejected: 0, percentage: 13 }
      ],
      // 科室列表数据
      deptList: [
        { deptId: '1', deptName: '办公室' },
        { deptId: '2', deptName: '财务科' },
        { deptId: '3', deptName: '人事科' },
        { deptId: '4', deptName: '技术科' },
        { deptId: '5', deptName: '业务科' }
      ],
      // 会议室列表数据
      roomList: [
        { id: '1', name: '会议室A' },
        { id: '2', name: '会议室B' },
        { id: '3', name: '会议室C' },
        { id: '4', name: '会议室D' },
        { id: '5', name: '会议室E' },
        { id: '6', name: '会议室F' },
        { id: '7', name: '会议室G' }
      ]
    }
  },
  created() {
    console.log('首页组件created生命周期开始')
    // 确保首页不被缓存，从缓存中移除
    if (this.$store.state.tagsView.cachedViews.includes('Index')) {
      this.$store.dispatch('tagsView/delCachedView', { name: 'Index' })
    }
    this.getDeptStats()
  },
  methods: {
    /** 获取科室统计数据 */
    async getDeptStats() {
      this.loading = true
      try {
        // 获取预约统计数据
        const response = await request({
          url: '/system/yuyue/countByDepartment',
          method: 'get'
        })

        // 从响应中提取数据，格式：{code: 200, msg: "操作成功", data: [...]}
        const statsData = response?.data || response || []
        
        // 过滤掉 department == 0 的数据
        const filteredData = statsData.filter(item => item.department != null && item.department !== 0)

        // 获取部门列表，建立部门ID到名称的映射
        const deptResponse = await listDept()
        const deptList = deptResponse?.data || deptResponse || []
        const deptMap = new Map()
        
        // 递归函数：处理树形结构的部门列表
        const processDeptList = (list) => {
          list.forEach(dept => {
            if (dept.deptId != null) {
              deptMap.set(dept.deptId, dept.deptName)
            }
            // 如果有子部门，递归处理
            if (dept.children && Array.isArray(dept.children) && dept.children.length > 0) {
              processDeptList(dept.children)
            }
          })
        }
        
        processDeptList(deptList)

        // 转换数据格式
        const mapped = filteredData.map(item => {
          const deptId = item.department
          const deptName = deptMap.get(deptId) || `部门${deptId}` || '未知部门'
          
          return {
            deptId: deptId,
            deptName: deptName,
            count: Number(item.yuyueCount || 0),
            approved: 0, // 接口返回数据中没有状态信息，暂时设为0
            pending: 0,
            rejected: 0,
            cancelled: 0,
            percentage: 0
          }
        })

        // 计算总数
        const total = mapped.reduce((sum, d) => sum + (Number.isFinite(d.count) ? d.count : 0), 0)

        // 计算占比
        this.deptStats = mapped.map(d => ({
          ...d,
          percentage: total > 0 ? Math.round((d.count / total) * 100) : 0
        }))

        // 更新统计卡片数据
        this.totalAppointmentCount = total
        // 初始化各状态数量
        this.approvedCount = 0
        this.rejectedCount = 0
        this.cancelledCount = 0

        // 并发获取各状态的数量
        const [response2, response3, response4] = await Promise.all([
          request({ url: '/system/yuyue/countByDepartmentAndState2', method: 'get' }),
          request({ url: '/system/yuyue/countByDepartmentAndState3', method: 'get' }),
          request({ url: '/system/yuyue/countQuxiaoState4', method: 'get' }).catch(() => ({ data: [] })) // 已取消状态，如果接口不存在则返回空数组
        ])

        // 通用求和函数，增强健壮性
        const sumCounts = (arr) => (Array.isArray(arr)
          ? arr.reduce((sum, item) => sum + (item?.yuyueCount || 0), 0)
          : 0)

        // 审核通过
        this.insertCountByDepartment(response2.data, 2)
        this.approvedCount = sumCounts(response2.data)

        // 审核拒绝
        this.insertCountByDepartment(response3.data, 3)
        this.rejectedCount = sumCounts(response3.data)

        // 已取消
        this.insertCountByDepartment(response4.data, 4)
        this.cancelledCount = sumCounts(response4.data)


        // 更新图表
        this.$nextTick(() => {
          setTimeout(() => {
            this.updateCharts()
          }, 300)
        })
      } catch (error) {
        console.error('获取统计数据失败:', error)
        this.$message.error('获取统计数据失败')
      } finally {
        this.loading = false
      }
    },

    // 根据科室id 插入通过、拒绝、待审核的数量
    // {
//     "msg": "操作成功",
//     "code": 200,
//     "data": [
//         {
//             "department": 0,
//             "yuyueCount": 1
//         },
//         {
//             "department": 103,
//             "yuyueCount": 1
//         },
//         {
//             "department": 100,
//             "yuyueCount": 1
//         }
//     ]
// }
    insertCountByDepartment(data, state) {
      if (!data || !Array.isArray(data)) return
      data.forEach(item => {
        const deptId = item.department
        const count = item.yuyueCount
        this.deptStats.forEach(dept => {
          if (dept.deptId === deptId) {
            if (state === 1) {
              dept.pending = count
            } else if (state === 2) {
              dept.approved = count
            } else if (state === 3) {
              dept.rejected = count
            } else if (state === 4) {
              dept.cancelled = (dept.cancelled || 0) + count
            }
          }
        })
      })
    },

    /** 更新图表数据 */
    updateCharts() {
      console.log('开始更新图表数据')
      console.log('deptStats数据:', this.deptStats)
      console.log('pieChart组件引用:', this.$refs.pieChart)

      // 准备饼图数据
      const pieData = this.deptStats.map(item => ({
        name: item.deptName,
        value: item.count
      }))

      const chartData = pieData.length > 0 ? pieData : [
        { name: '暂无数据', value: 1 }
      ]

      console.log('准备传递给图表的最终数据:', chartData)

      if (this.$refs.pieChart) {
        console.log('调用图表组件的updateData方法')
        console.log('图表组件存在，正在更新数据...')
        this.$refs.pieChart.updateData(chartData)
      } else {
        console.error('图表组件引用不存在，尝试使用window对象')
        if (window.pieChartInstance) {
          console.log('通过window对象更新图表数据')
          window.pieChartInstance.setOption({
            tooltip: {
              trigger: 'item',
              formatter: '{b}: {c} ({d}%)'
            },
            legend: {
              orient: 'vertical',
              left: 'left',
              top: '20%',
              textStyle: {
                fontSize: 12
              }
            },
            series: [
              {
                name: '科室预约占比',
                type: 'pie',
                radius: ['40%', '70%'],
                center: ['60%', '50%'],
                avoidLabelOverlap: false,
                label: {
                  show: true,
                  fontSize: 12,
                  formatter: '{b}: {d}%'
                },
                emphasis: {
                  label: {
                    show: true,
                    fontSize: 14,
                    fontWeight: 'bold'
                  }
                },
                labelLine: {
                  show: true
                },
                data: chartData,
                animationEasing: 'cubicInOut',
                animationDuration: 2000
              }
            ],
            color: ['#409EFF', '#67C23A', '#E6A23C', '#F56C6C', '#909399', '#795AEE', '#00C4CC', '#FF8C42']
          }, true)
        } else {
          console.error('window.pieChartInstance也不存在')
        }
      }
    },


    /** 刷新数据 */
    refreshData() {
      this.getDeptStats()
    },

    /** 处理统计卡片点击事件 */
    handleCardClick(state) {
      // 跳转到预约列表页面，并传递状态参数
      const query = {}
      if (state !== 'all') {
        query.state = state
      }
      this.$router.push({
        path: '/meeting/index',
        query: query
      })
    }
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
  background: #f8f9fa;
  min-height: calc(100vh - 84px);
}

/* 统计卡片容器 */
.stat-cards-container {
  display: flex;
  gap: 20px;
  margin-bottom: 30px;
  width: 100%;
}

/* 统计卡片样式 */
.stat-card {
  flex: 1;
  border-radius: 15px;
  padding: 20px;
  color: white;
  display: flex;
  align-items: center;
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
  transition: transform 0.3s ease;
  cursor: pointer;
  min-height: 100px;
  width: 100%;
}

.stat-card:hover {
  transform: translateY(-5px);
}

.stat-card-primary {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.stat-card-success {
  background: linear-gradient(135deg, #67c23a 0%, #85ce61 100%);
}

.stat-card-warning {
  background: linear-gradient(135deg, #e6a23c 0%, #ebb563 100%);
}

.stat-card-danger {
  background: linear-gradient(135deg, #f56c6c 0%, #f78989 100%);
}

.stat-card-info {
  background: linear-gradient(135deg, #909399 0%, #a6a9ad 100%);
}

.stat-icon {
  width: 50px;
  height: 50px;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
}

.stat-icon i {
  font-size: 24px;
}

.stat-number {
  font-size: 28px;
  font-weight: bold;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
  opacity: 0.9;
}

/* 图表容器样式 */
.chart-container, .table-container {
  background: white;
  border-radius: 15px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  overflow: hidden;
}

.chart-header, .table-header {
  padding: 20px 25px;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  min-height: 80px;
}

.chart-title, .table-title {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #2c3e50;
}

.chart-body, .table-body {
  padding: 25px;
}

/* 表格样式优化 */
.status-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .stat-cards-container {
    gap: 15px;
  }

  .stat-card {
    padding: 15px;
    min-height: 90px;
  }

  .stat-number {
    font-size: 24px;
  }

  .stat-icon {
    width: 45px;
    height: 45px;
  }

  .stat-icon i {
    font-size: 20px;
  }
}

@media (max-width: 768px) {
  .app-container {
    padding: 15px;
  }

  .stat-cards-container {
    flex-wrap: wrap;
    gap: 15px;
  }

  .stat-card {
    flex: 1 1 calc(50% - 7.5px);
    min-width: calc(50% - 7.5px);
    padding: 12px;
    min-height: 80px;
  }

  .stat-number {
    font-size: 20px;
  }

  .stat-label {
    font-size: 12px;
  }

  .stat-icon {
    width: 40px;
    height: 40px;
    margin-right: 10px;
  }

  .stat-icon i {
    font-size: 18px;
  }
}

@media (max-width: 480px) {
  .stat-card {
    flex: 1 1 100%;
    min-width: 100%;
  }
}

/* ECharts主题样式 */
.chart-container .chart-body {
  background: #fafafa;
}
</style>
